# 读取chengyu.txt文件中的四字成语
with open('chengyu.txt', 'r', encoding='utf-8') as file:
    chengyu_list = file.readlines()

# 提取成语的不同格式
formats = ['AABB', 'AABC', 'ABAC', 'ABCA']

# 将不同格式的成语分别存入对应的文件中
for format in formats:
    # 创建文件名
    file_name = f'CY{format}.txt'
    # 打开文件并写入对应格式的成语
    with open(file_name, 'w', encoding='utf-8') as output_file:
        for chengyu in chengyu_list:
            chengyu = chengyu.strip()
            # 检查成语长度是否为4
            if len(chengyu) != 4:
                continue
            # 检查成语是否符合指定格式
            if format == 'AABB':
                if chengyu[0] == chengyu[1] and chengyu[2] == chengyu[3]:
                    output_file.write(chengyu + '\n')
            elif format == 'AABC':
                if chengyu[0] == chengyu[1] and chengyu[0] != chengyu[2] and chengyu[2] != chengyu[3]:
                    output_file.write(chengyu + '\n')
            elif format == 'ABAC':
                if chengyu[0] != chengyu[1] and chengyu[1] == chengyu[2] and chengyu[0] == chengyu[3]:
                    output_file.write(chengyu + '\n')
            elif format == 'ABCA':
                if chengyu[0] != chengyu[1] and chengyu[0] == chengyu[2] and chengyu[1] == chengyu[3]:
                    output_file.write(chengyu + '\n')

print("成语已按指定格式存入文件中。")
